﻿namespace Rio.Manager.Application.Views
{
	using System;
	using System.Windows;
	using System.Windows.Controls;
	using Rio.Framework.Pages;
	using Rio.Manager.Application.ViewModel.Administration;
	using Rio.Framework.Localisation;
	using NetBay.Core.BusinessEntities.Barcodes;
	using Telerik.Windows.Controls.GridView;
    using GalaSoft.MvvmLight.Messaging;

    public partial class BarCodeAddTabView : UserControl
	{
		#region Constructors

		public BarCodeAddTabView()
		{
			InitializeComponent();

            Unloaded += (s, e) => Messenger.Default.Unregister<NotificationMessage>(this, OrganizationAndFolderType_ReLaod); 

            Messenger.Default.Register<NotificationMessage>(this, OrganizationAndFolderType_ReLaod);    
		}
	   
		#endregion Constructors       

		#region Event
	    
		/// <summary>Grid view parameters documents validation.</summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void radGridView_BarcoDe_Separator_Document_Parameters_Add_CellValidating(object sender, Telerik.Windows.Controls.GridViewCellValidatingEventArgs e)
		{
			//variable initialization.
			bool l_bIsValid = true;
			string l_sCellHeader = string.Empty;
            string l_sAllParamCodeValue = string.Empty;
			string l_sErrorValidationMessage = Resx.GetLabel(ResxRioManager.BARCODE_MSG_TITLE_ERROR_VALIDATION_PARAMETER_DOCUMENT);
			BarcodeDocumentSeparator l_oCurrentItemToAdd = new BarcodeDocumentSeparator();
			GridViewCell cell = e.Cell;
             
			//Validation test treatment.
			switch (cell.Column.UniqueName)
			{
				case "ParamCode":
					l_sCellHeader = (DataContext as BarCodeAddTabViewModel).HeaderBarCodeSeparatorDocumentId;

                    //Cell new value. 
                    if (radGridView_BarcoDe_Separator_Document_Parameters_Add.CurrentCell.Value != null)
                    {
                        if ((string)e.NewValue == radGridView_BarcoDe_Separator_Document_Parameters_Add.CurrentCell.Value.ToString())
                        {
                            return;
                        }
                    }                   

                    //New Value.
                    foreach (BarcodeDocumentSeparator l_oGridViewBarCodeDocumentItem in radGridView_BarcoDe_Separator_Document_Parameters_Add.Items)
                    {
                        l_sAllParamCodeValue = l_sAllParamCodeValue + l_oGridViewBarCodeDocumentItem.ParamCode + ";";
                    }
                    l_sAllParamCodeValue = l_sAllParamCodeValue.Substring(0, l_sAllParamCodeValue.Length - 1);
                    l_bIsValid = ValidateParamCode((string)e.NewValue, l_sAllParamCodeValue);
					if (!l_bIsValid)
					{
						l_sErrorValidationMessage += Environment.NewLine + string.Format(Resx.GetLabel(ResxRioManager.BARCODE_MSG_ERROR_VALIDATION_PARAMETER_DOCUMENT_PARAMCODE),l_sCellHeader); 
					}
					break;
				case "InfLimit":
					l_sCellHeader = (DataContext as BarCodeAddTabViewModel).HeaderBarCodeSeparatorDocumentInfLimit;
					l_oCurrentItemToAdd = (BarcodeDocumentSeparator)radGridView_BarcoDe_Separator_Document_Parameters_Add.Items.CurrentAddItem;
                    if (l_oCurrentItemToAdd == null)
                    {
                        l_oCurrentItemToAdd = (BarcodeDocumentSeparator)radGridView_BarcoDe_Separator_Document_Parameters_Add.Items.CurrentEditItem;
                    }
					l_bIsValid = ValidateInfLimit(e.NewValue.ToString(), l_oCurrentItemToAdd.SupLimit, "Inf");
					if (!l_bIsValid)
					{
						l_sErrorValidationMessage += Environment.NewLine + string.Format(Resx.GetLabel(ResxRioManager.BARCODE_MSG_ERROR_VALIDATION_PARAMETER_DOCUMENT_INFLIMIT),l_sCellHeader).Replace("\\n",Environment.NewLine); 
					}
					break;
				case "SupLimit":
					l_sCellHeader = (DataContext as BarCodeAddTabViewModel).HeaderBarCodeSeparatorDocumentSupLimit;
					l_oCurrentItemToAdd = (BarcodeDocumentSeparator)radGridView_BarcoDe_Separator_Document_Parameters_Add.Items.CurrentAddItem;
                    if (l_oCurrentItemToAdd == null)
                    {
                        l_oCurrentItemToAdd = (BarcodeDocumentSeparator)radGridView_BarcoDe_Separator_Document_Parameters_Add.Items.CurrentEditItem;
                    }
					l_bIsValid = ValidateInfLimit(e.NewValue.ToString(), l_oCurrentItemToAdd.InfLimit, "Sup");
					if (!l_bIsValid)
					{
						l_sErrorValidationMessage += Environment.NewLine + string.Format(Resx.GetLabel(ResxRioManager.BARCODE_MSG_ERROR_VALIDATION_PARAMETER_DOCUMENT_SUPLIMIT), l_sCellHeader).Replace("\\n", Environment.NewLine);
					}
					break;

			}
			if (!l_bIsValid)
			{
				this.MarkCell(cell, l_sErrorValidationMessage);
			}
			else
			{
				this.RestoreCell(cell);
			}

			e.ErrorMessage = l_sErrorValidationMessage;
			e.IsValid = l_bIsValid;	
		}

		/// <summary>Param Code validation.</summary>
		/// <param name="p_sParamCodeValue">ParamCode Value</param>
		/// <returns>Validation boolean.</returns>
		private static bool ValidateParamCode(string p_sParamCodeValue, string p_sAllParamValue)
		{
			//Variable initialization.
            string[] l_sAllParamValue = p_sAllParamValue.Split(new char[] { ';' });

			//Validation test.
			if (p_sParamCodeValue == null || p_sParamCodeValue.Length != 3)
			{
                return false;
			}
            foreach (string l_sParamValue in l_sAllParamValue)
            {
                if (l_sParamValue == p_sParamCodeValue)
                {
                    return false;
                }
            }

            return true;
		}

        /// <summary>Inferiore limit validation.</summary>
        /// <param name="p_iSecondLimiteValue">Second Limite value to test.</param>
        /// <param name="p_sLimitInfOrSupToTest">Limit to test?.</param>
        /// <param name="p_sLimitValueToTest">Limite value to test.</param>
        /// <returns>Validation boolean.</returns>
        private static bool ValidateInfLimit(string p_sLimitValueToTest,int p_iSecondLimiteValue,string p_sLimitInfOrSupToTest)
		{
			//Variables initialization.
			Boolean l_bValidate = true;

            //Test.
			try
			{
				//Value is an integer.
				int l_iLimitToTest = Int32.Parse(p_sLimitValueToTest);

				//Logic test limits.
				if (p_sLimitInfOrSupToTest.ToLower() == "inf")
				{
					if (l_iLimitToTest > p_iSecondLimiteValue)
					{
						l_bValidate = false;                            
					}
				}
				else
				{
					if (l_iLimitToTest < p_iSecondLimiteValue)
					{
						l_bValidate = false;  
					}
				}
				return l_bValidate;
			}
			catch (FormatException)
			{                
				return false;  
			}            
		}

        /// <summary>Cells validation.</summary>
        /// <param name="cell"></param>
        /// <param name="validationText"></param>
		private void MarkCell(Control cell, string validationText)
		{
			ToolTipService.SetToolTip(cell, validationText);
		}

        /// <summary>Cells restauration.</summary>
        /// <param name="cell"></param>
		private void RestoreCell(Control cell)
		{
			ToolTipService.SetToolTip(cell, null);
		}
		
		/// <summary>Validation Identifiant barcode.</summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TextBox_BarCodeId_LostFocus(object sender, RoutedEventArgs e)
		{
			//Variable initialization.
			TextBox l_oBarCodeId = e.OriginalSource as TextBox;
            Boolean l_oAddButtonIsEnablePropertie = (DataContext as BarCodeAddTabViewModel).IsEnabledAddBarCodeButton;
            Boolean l_oUpdateButtonIsEnablePropertie = (DataContext as BarCodeAddTabViewModel).IsEnabledUpdateBarCodeButton;

			//Test.
			if ((l_oBarCodeId.Text.Length != TextBox_BarCodeId.MaxLength) && (TextBox_BarCodeId.Text != string.Empty))
			{
				 MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.BARCODE_MSG_ERROR_VALIDATION_BARCODE_ID), (DataContext as BarCodeAddTabViewModel).BarCodeIdentifierAddTitle), MessageBoxButtons.Ok, MessageBoxIcon.Error);
                 L_oMessage.Show();
                L_oMessage.Closed += (s, ev) =>
                {
                    (DataContext as BarCodeAddTabViewModel).IsEnabledAddBarCodeButton = l_oAddButtonIsEnablePropertie;
                    (DataContext as BarCodeAddTabViewModel).IsEnabledUpdateBarCodeButton = l_oUpdateButtonIsEnablePropertie;
                    (DataContext as BarCodeAddTabViewModel).BarCodeIdentifierAdd = string.Empty;
                };           
			}
		}

		/// <summary>Validation prefix barcode.</summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TextBox_BarCodePrefix_LostFocus(object sender, RoutedEventArgs e)
		{
			//Variable initialization.
			TextBox l_oBarCodePrefix = e.OriginalSource as TextBox;
            Boolean l_oAddButtonIsEnablePropertie = (DataContext as BarCodeAddTabViewModel).IsEnabledAddBarCodeButton;
            Boolean l_oUpdateButtonIsEnablePropertie = (DataContext as BarCodeAddTabViewModel).IsEnabledUpdateBarCodeButton;

			//Test.
			if ((l_oBarCodePrefix.Text.Length != TextBox_BarCodePrefix.MaxLength) && (l_oBarCodePrefix.Text != string.Empty))
			{
				MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.BARCODE_MSG_ERROR_VALIDATION_BARCODE_PREFIX), (DataContext as BarCodeAddTabViewModel).BarCodeTypologyPrefixAddTitle), MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessage.Show();
                L_oMessage.Closed += (s, ev) =>
                {
                    (DataContext as BarCodeAddTabViewModel).IsEnabledAddBarCodeButton = l_oAddButtonIsEnablePropertie;
                    (DataContext as BarCodeAddTabViewModel).IsEnabledUpdateBarCodeButton = l_oUpdateButtonIsEnablePropertie;
                    (DataContext as BarCodeAddTabViewModel).BarCodeTypologyPrefixAdd = string.Empty;
                }; 
			}
		}

		/// <summary>Validation Lower limit</summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void UppDownLowerBoundLimit_LostFocus(object sender, RoutedEventArgs e)
		{
			//Test.
			BoundLimitTest("Inf");
		}

		/// <summary>Validation Upper limit</summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void UppDownUpperBoundLimit_LostFocus(object sender, RoutedEventArgs e)
		{
			//Test.
			BoundLimitTest("Sup");
		}

		/// <summary>RadGridView Validation.</summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void radGridView_BarcoDe_Separator_Document_Parameters_Add_RowValidated(object sender, Telerik.Windows.Controls.GridViewRowValidatedEventArgs e)
		{
			//RadGridView validation is ok.
			(DataContext as BarCodeAddTabViewModel).IsEditingRadGridViewBarcoDeSeparatorDocumentParametersAdd = false;
		}

		/// <summary>Change Barcode function enable.</summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void chModifyFunctionBarCode_Click(object sender, RoutedEventArgs e)
		{  
            //Variable initialization.
            Boolean l_oAddButtonIsEnablePropertie = (DataContext as BarCodeAddTabViewModel).IsEnabledAddBarCodeButton;
            Boolean l_oUpdateButtonIsEnablePropertie = (DataContext as BarCodeAddTabViewModel).IsEnabledUpdateBarCodeButton;

			if (chModifyFunctionBarCode.IsChecked == true)
			{
				//Enable or note the function changment.
				MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, (Resx.GetLabel(ResxRioManager.BARCODE_MSG_CHANGE_FUNCTION).Replace("\\n", Environment.NewLine)), MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                L_oMessage.Show();
				L_oMessage.Closed += (s, ev) =>
				{
                    (DataContext as BarCodeAddTabViewModel).IsEnabledAddBarCodeButton = l_oAddButtonIsEnablePropertie;
                    (DataContext as BarCodeAddTabViewModel).IsEnabledUpdateBarCodeButton = l_oUpdateButtonIsEnablePropertie;
					if (L_oMessage.Result == MessageBoxResult.Yes)
					{
						//Function change combobox is enable.
						(DataContext as BarCodeAddTabViewModel).IsEnabledcbFunctionName = true;
					}
					else
					{
						//Function change combobox is not enable.
						(DataContext as BarCodeAddTabViewModel).IsEnabledcbFunctionName = false;
						chModifyFunctionBarCode.IsChecked = false;
					}
				};
				return;
			}
			else
			{
				//Function change combobox is not enable.
				(DataContext as BarCodeAddTabViewModel).IsEnabledcbFunctionName = false;
			}

		}

        /// <summary>RadGridView begin edit.</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radGridView_BarcoDe_Separator_Document_Parameters_Add_BeginningEdit(object sender, Telerik.Windows.Controls.GridViewBeginningEditRoutedEventArgs e)
        {
            //RadGridView begin edit.
            (DataContext as BarCodeAddTabViewModel).IsEditingRadGridViewBarcoDeSeparatorDocumentParametersAdd = true;
        }

        /// <summary>RadGridView prepared for edit.</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radGridView_BarcoDe_Separator_Document_Parameters_Add_PreparedCellForEdit(object sender, Telerik.Windows.Controls.GridViewPreparingCellForEditEventArgs e)
        {
            //Variable initialization.
            string l_sColumnUniqueNameToChange = e.Column.UniqueName;
            string l_sColumnUniqueNameIdentifiant = string.Empty;

            //Boolean value test and change value.
            if ((l_sColumnUniqueNameToChange == "PdfMerge") || (l_sColumnUniqueNameToChange == "DeleteBarCodePage") || (l_sColumnUniqueNameToChange == "ErrorManagment"))
            {
                //Retrieves all the value for updating.
                BarcodeDocumentSeparator l_oBarcodeDocSepSelect = ((BarcodeDocumentSeparator)e.Row.Item);
                l_sColumnUniqueNameIdentifiant = l_oBarcodeDocSepSelect.ParamCode;

                //Update Value on the good item property.
                foreach (BarcodeDocumentSeparator l_oBarCodeSeparatorDocumentItem in (DataContext as BarCodeAddTabViewModel).BarCodeSeparatorDocumentParametersList)
                {
                    if (l_oBarCodeSeparatorDocumentItem.ParamCode == l_sColumnUniqueNameIdentifiant)
                    {
                        switch (e.Column.UniqueName)
                        {
                            case "PdfMerge":
                                l_oBarCodeSeparatorDocumentItem.PdfMerge = l_oBarCodeSeparatorDocumentItem.PdfMerge ? false : true;
                                break;
                            case "DeleteBarCodePage":
                                l_oBarCodeSeparatorDocumentItem.DeleteBarCodePage = l_oBarCodeSeparatorDocumentItem.DeleteBarCodePage ? false : true;
                                break;
                            case "ErrorManagment":
                                l_oBarCodeSeparatorDocumentItem.ErrorManagment = l_oBarCodeSeparatorDocumentItem.ErrorManagment ? false : true;
                                break;
                            default:
                                break;
                        }
                        break;
                    }                    
                }
            }
        }

		#endregion Event

		#region method

		/// <summary>Method limit test.</summary>
		/// <param name="p_sBoundToTest"></param>
		private void BoundLimitTest(string p_sBoundToTest)
		{   
			//Variable initialization.
			string l_sMessage = string.Empty;
            Boolean l_oAddButtonIsEnablePropertie = (DataContext as BarCodeAddTabViewModel).IsEnabledAddBarCodeButton;
            Boolean l_oUpdateButtonIsEnablePropertie = (DataContext as BarCodeAddTabViewModel).IsEnabledUpdateBarCodeButton;
            
			//Test.
			if (Convert.ToInt32(UppDownLowerBoundLimit.Value) > Convert.ToInt32(UppDownUpperBoundLimit.Value))
			{
				//Bound to modify.
				if (p_sBoundToTest.ToLower() == "inf")
				{
					l_sMessage = Resx.GetLabel(ResxRioManager.BARCODE_MSG_ERROR_VALIDATION_INF_BOUND);
					UppDownLowerBoundLimit.Value = 0;
				}
				else
				{ 
					l_sMessage = Resx.GetLabel(ResxRioManager.BARCODE_MSG_ERROR_VALIDATION_SUP_BOUND);
					UppDownUpperBoundLimit.Value = 0;
				} 
			 
				//User message. 
				MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, l_sMessage, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessage.Show();
                L_oMessage.Closed += (s, ev) =>
                {
                    (DataContext as BarCodeAddTabViewModel).IsEnabledAddBarCodeButton = l_oAddButtonIsEnablePropertie;
                    (DataContext as BarCodeAddTabViewModel).IsEnabledUpdateBarCodeButton = l_oUpdateButtonIsEnablePropertie;
                };
			}
		}
        
        /// <summary>Relaod Organization and FolderType control.</summary>
        /// <param name="p_oMsg">Notification Message.</param>
        private void OrganizationAndFolderType_ReLaod(NotificationMessage p_oMsg = null)
        {
            //Reload the BindableOrganizationFolderTypePanel.
            if ((p_oMsg != null) && (!p_oMsg.Notification.Equals("RefreshConsultBarcode")))
            {
                BarcodeSeparatorType l_oBarcodeSeparatorType = (BarcodeSeparatorType) System.Enum.Parse(typeof (BarcodeSeparatorType), p_oMsg.Notification, true);

                switch (l_oBarcodeSeparatorType)
                {
                    case BarcodeSeparatorType.None:
                        break;
                    case BarcodeSeparatorType.FolderSeparator:
                        UCOrganizationsFolderTypeBarCodeSeparatorFolder.organizationTypePanelBase_Loaded(this, null);
                        break;
                    case BarcodeSeparatorType.DocumentSeparator:
                        UCOrganizationsFolderTypeBarCodeSeparatorDocument.organizationTypePanelBase_Loaded(this, null);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(
                            "BarCodeAddTabView.OrganizationAndFolderTypeFolder_ReLaod: This barcode separator type: " +
                            l_oBarcodeSeparatorType.ToString() + " isn't supported");
                }
            }
        }

        #endregion method
	}
}